<template>
  <div>
    <div class="signin">
      <div @click="exit()" v-if="LoginState==2">退出登录</div>
			<div class="name" v-if="LoginState==2">{{$store.state.nickname}}</div>
      <div @click='handlelogin()' class="name" v-else>未登录</div>
			<div class="tx">
        <el-avatar :src="LoginState==2?$store.state.avatarUrl:''"></el-avatar>
      </div>

    </div>

    <el-dialog label="登录注册" class="bx" :visible.sync="dialogFormVisible" modal :append-to-body='true'>
      <!-- <tered></tered> -->
      <!-- 登录 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
        v-if="active==1">
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model.number="ruleForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tellogin() ">登录</el-button>
          <el-button @click="active=2">注册</el-button>

        </el-form-item>
      </el-form>
      <el-form :model="ruleForm" status-icon ref="ruleForm" label-width="100px" :rules="rules" class="demo-ruleForm"
        v-if="active==2">
        <el-form-item label="手机号" prop="phone" width="10px">
          <el-input v-model.number="ruleForm.phone" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="验证码" width="10px" prop="captcha">
          <el-input v-model="ruleForm.captcha" placeholder="请输入短信验证码"></el-input>
        </el-form-item>
        <el-form-item label="昵称" width="10px" prop="nickname">
          <el-input v-model="ruleForm.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit()">注册</el-button>
          <el-button @click="goVerification()">获取验证码
          </el-button>
          <el-button @click="active=1">登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
// import tered from "../nav/registered";
import { API } from "../../common/constant";
import axios from "axios";
export default {
  data() {
    var validatePass = (value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    return {
      datalist: [],
      dialogFormVisible: false,

      modal: true,
      ruleForm: {
        // 登录手机号
        username: "",
        // 登录密码
        password: "",
        // 注册手机号
        phone: "",
        // 注册密码
        pass: "",
        // 注册验证码
        captcha: "",
        // 注册昵称
        nickname: "",
      },
			// 校验规则
      rules: {
        // 登录账号
        username: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "请输入合法的手机号" },
        ],
        // 登录密码
        password: [
          {
            validate: validatePass,
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          { min: 6, max: 18, message: "密码到6~18位" },
        ],
        // 注册账号
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern: /^1[3456789]\d{9}$/, message: "请输入合法的手机号" },
        ],
        // 注册密码
        pass: [
          {
            validate: validatePass,
            required: true,
            message: "请输入密码",
            trigger: "blur",
          },
          { min: 6, max: 18, message: "密码到6~18位" },
        ],
      },
      active: 1,
      sms: "",
      names: "未登录",
      // 用户id
      id: "",
			// 用户登录状态
			LoginState:1
    };
  },
  components: {
    // tered,
  },
  created() {
    this.handlePhone();
  },
  methods: {
		// 退出登录
		exit(){
			axios.get(`${API}/logout`).then(res=>{
				console.log(res);
				
				window.sessionStorage.clear()
				this.LoginState=1
			})
		},
	
    // 关闭窗口
    handlelogin() {
      this.dialogFormVisible = true;
    },
    // 登录方法
    tellogin() {
      if (this.testPhoneNumber() && this.testPassword()) {
        axios
          .get(`${API}/login/cellphone`, {
            params: {
              phone: this.ruleForm.username,
              password: this.ruleForm.password,
            },
          })
          .then((res) => {
            if (res.data.code == 200) {
              // window.sessionStorage.setItem("token", res.data.cookie);
							
              this.$message.success("登录成功");
              console.log(res.data);
              this.sms = res.data.profile.backgroundUrl;
              this.names = res.data.profile.nickname;
              this.dialogFormVisible = false;
							// 把用户名和token放入到sessionStorage
							// sessionStorage.setItem('userName',res.data.profile.nickname)
							// sessionStorage.setItem('avatarUrl',res.data.profile.avatarUrl)
							// sessionStorage.setItem('userToken',res.data.token)

							let obj = {
								nickname:res.data.profile.nickname,
								avatarUrl:res.data.profile.avatarUrl,
								token:res.data.token,
							}
							// sessionStorage.setItem('userstate',JSON.stringify(obj))
//这块。登录成功以后。把nickname，avatarUrl，token调用vuex存到vuex和session里面、
							this.$store.dispatch('SETUSERSTATE',obj)
							// console.log(this.$store.dispatch('SETUSERSTATE',obj));
							// 保存到vuex中
							// this.$store.dispatch('SETUser',res.data.profile.nickname);
							// this.$store.dispatch('setToken',res.data.token);
							this.LoginState=2
              //   console.log(sessionStorage.getItem('token'));
              // console.log(res.data.profile.id);
              // this.data = res.data.profile.avatarUrl;
            } else if (res.data.code !== 200) {
              this.$message.error(res.data.message);
            }
          });
      } else {
        alert("请输入合法的手机号或密码");
      }
    },
    // 校验登录手机号
    testPhoneNumber() {
      return /^1[3456789]\d{9}$/.test(this.ruleForm.username);
    },
    // 校验登录密码长度
    testPassword() {
      return this.ruleForm.password.length > 6;
    },

    // 注册方法
    // 思路 先验证手机号是否已被注册 在根据手机号发送验证码 校验验证码 最后发送注册请求
    // 1校验手机号是否已被注册
    handlePhone() {
      // 写个注释把 return 返回promise 第一步 先验证手机号是否已被注册
      return axios
        .get(`${API}/cellphone/existence/check`, {
          params: {
            phone: this.ruleForm.phone,
          },
        })
        .then((res) => {
          if (res.data.exist === 1) {
            this.$message.success("该手机号已注册 请登录");
            this.active = 1;
            return false;
          } else {
            return true;
          }
        })
        .catch((e) => e);
    },
    // 2发送验证码
    goVerification() {
      axios
        .get(`${API}/captcha/sent`, {
          params: {
            phone: this.ruleForm.phone,
            captcha: this.ruleForm.captcha,
          },
        })
        .then((res) => {
          console.log(res);
        });
    },
    // 3校验验证码 返回promise
    checkVerification() {
      return axios
        .get(`${API}/captcha/verify`, {
          params: {
            phone: this.ruleForm.phone,
            captcha: this.ruleForm.captcha,
          },
        })
        .then((res) => {
          return res;
        });
    },
    // 4发送注册请求
    registered() {
      return axios
        .get(`${API}/register/cellphone`, {
          params: {
            phone: this.ruleForm.phone,
            captcha: this.ruleForm.captcha,
            password: this.ruleForm.pass,
            nickname: this.ruleForm.nickname,
          },
        })
        .then((res) => {
					console.log(res)
					return res
        });
    },
    //注册
    async submit() {
      let flag = await this.handlePhone(); //是否注册
      if (flag) {
        try {
          let code = await this.checkVerification(); //校验验证码
          if(code){
              this.registered()
							this.$message.success('注册成功');
					}
        } catch (e) {
					 this.$message.error(e.data.message);
				}
      }
    },
  },
};
</script>
<style lang='less'>
.signin {
  display: flex;
  position: absolute;
  top: 0px;
  left: 1050px;
  .tx {
    display: inline-block;
    margin-top: 15px;
  }
}

.bx {
  width: 1300px;
}
/* 下拉列表 */
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.name {
  display: inline-block;
  padding-bottom: 10px;
}
</style>